import datetime
import decimal
import random
import time
from decimal import Decimal

import requests

from orderSharing.retailOrderSharing import RetailOrderSharing


class RegistrationActivities:

    def __init__(self):
        self.retailOrderSharing = RetailOrderSharing()

    # 随机生成电话号码
    def creat_phone(self):
        # 第二位
        second = [3, 4, 5, 7, 8][random.randint(0, 4)]

        # 第三位的值根据第二位来确定
        third = {
            3: random.randint(0, 9),
            4: [5, 7, 9][random.randint(0, 2)],
            5: [i for i in range(10) if i != 4][random.randint(0, 8)],
            7: [i for i in range(10) if i not in [4, 9]][random.randint(0, 7)],
            8: random.randint(0, 9)
        }[second]
        # 后8位随机抽取
        suffix = ''
        for x in range(8):
            suffix = suffix + str(random.randint(0, 9))
        # 拼接
        return "1{}{}{}".format(second, third, suffix)

    # 代理参加活动
    def participate_in_the_event_as_an_agent(self, agentId, userId, activityId, capping, phone, statisticsType):

        requests.request("POST", url="https://test.api.vodeshop.com/api/sms/user-login",
                         json={"mobile": phone})
        time.sleep(5)

        print("userId：", userId)
        agentUserToken = requests.request("POST", url="https://test.api.vodeshop.com/api/auth/login/mobile",
                                     json={"mobile": phone, "password": "", "code": "111111"}).json()
        print("agentUserToken：", agentUserToken)
        agentToken = agentUserToken["data"]["token_type"] + " " + agentUserToken["data"]["access_token"]

        # 参加报名活动
        requests.request("POST", url="https://test.api.vodeshop.com/svc/marketing-svc/api/v1/activity/sign",
                         headers={"x-request-from": "web", "x-requested-with": "XMLHttpRequest",
                                  "authorization": agentToken},
                                     json={"user_id":userId,"activity_id":activityId})

        if statisticsType == 1:
            self.retailOrderSharing.session.commit()
            parent = self.retailOrderSharing.session.execute(
                "select ra1.parent_id, ra2.user_id, u.mobile\
                        from retail_agents ra1\
                        inner join users u on u.id = ra2.user_id\
                        inner join retail_agents ra2 on ra2.id = ra1.parent_id\
                        where ra1.id = :agentId limit 1",
                params={"agentId": agentId}).first()
            print("parent：", parent)
            print("capping：", capping)

            if parent != None:
                if parent[0] > 0:
                    if capping == False:
                        if parent[0] == 1:
                            capping = True

                        self.participate_in_the_event_as_an_agent(parent[0], parent[1], activityId, capping, parent[2], statisticsType)

    # 上级用户参加活动
    def superiors_participate_in_activities(self, userId, activityId, bindStoreId, statisticsType, categoryId):
        self.retailOrderSharing.session.commit()
        referee_user = self.retailOrderSharing.session.execute(
            "select ru.referee_user_id, u.mobile\
                    from retail_users ru\
                    inner join users u on u.id = ru.referee_user_id\
                    where ru.user_id = :userId",
            params={"userId": userId}).first()

        self.retailOrderSharing.session.commit()
        user_vip_level = self.retailOrderSharing.session.execute(
            "select vip_level from retail_vips where user_id = :userId limit 1",
            params={"userId": referee_user[0]}).first()
        print("user_vip_level：", user_vip_level)

        if user_vip_level != None:
            requests.request("POST", url="https://test.api.vodeshop.com/api/sms/user-login",
                             json={"mobile": referee_user[1]})
            time.sleep(5)

            print("referee_user：", referee_user)
            superiorUserToken = requests.request("POST", url="https://test.api.vodeshop.com/api/auth/login/mobile",
                                         json={"mobile": referee_user[1], "password": "", "code": "111111"}).json()
            print("superiorUserToken：", superiorUserToken)
            superiorToken = superiorUserToken["data"]["token_type"] + " " + superiorUserToken["data"]["access_token"]

            # 参加报名活动
            requests.request("POST", url="https://test.api.vodeshop.com/svc/marketing-svc/api/v1/activity/sign",
                             headers={"x-request-from": "web", "x-requested-with": "XMLHttpRequest",
                                      "authorization": superiorToken},
                             json={"user_id": referee_user[0], "activity_id": activityId})

        if statisticsType == 1:
            if user_vip_level == None:
                self.superiors_participate_in_activities(referee_user[0], activityId, bindStoreId, statisticsType, categoryId)
            else:
                if user_vip_level[0] == 3:
                    if categoryId == 20 or categoryId == 21:
                        self.retailOrderSharing.session.commit()
                        retail_agent = self.retailOrderSharing.session.execute(
                            "select rs.retail_agent_id, ra.user_id, u.mobile\
                                    from retail_stores rs\
                                    inner join users u on u.id = ra.user_id\
                                    inner join retail_agents ra on ra.id = rs.retail_agent_id\
                                    where rs.id = :storeId limit 1",
                            params={"storeId": bindStoreId}).first()

                        self.participate_in_the_event_as_an_agent(retail_agent[0], retail_agent[1], activityId, False, retail_agent[2], statisticsType)

                else:
                    self.superiors_participate_in_activities(referee_user[0], activityId, bindStoreId, statisticsType, categoryId)

    # 自身参加活动
    def self_participation(self, userId, activityId, bindStoreId, statisticsType, phone, stop):
        requests.request("POST", url="https://test.api.vodeshop.com/api/sms/user-login",
                         json={"mobile": phone})
        time.sleep(5)

        print("userId：", userId)
        selfUserToken = requests.request("POST", url="https://test.api.vodeshop.com/api/auth/login/mobile",
                                             json={"mobile": phone, "password": "",
                                                   "code": "111111"}).json()
        print("selfUserToken：", selfUserToken)
        selfToken = selfUserToken["data"]["token_type"] + " " + selfUserToken["data"][
            "access_token"]

        # 参加报名活动
        requests.request("POST", url="https://test.api.vodeshop.com/svc/marketing-svc/api/v1/activity/sign",
                         headers={"x-request-from": "web", "x-requested-with": "XMLHttpRequest",
                                  "authorization": selfToken},
                         json={"user_id": userId, "activity_id": activityId})

        if stop == True:
            return

        if statisticsType == 1:
            self.retailOrderSharing.session.commit()
            referee_user = self.retailOrderSharing.session.execute(
                "select ru.referee_user_id, u.mobile\
                        from retail_users ru\
                        inner join users u on u.id = ru.referee_user_id\
                        where ru.user_id = :userId",
                params={"userId": userId}).first()

            self.retailOrderSharing.session.commit()
            user_vip_level = self.retailOrderSharing.session.execute(
                "select vip_level from retail_vips where user_id = :userId limit 1",
                params={"userId": referee_user[0]}).first()
            print("user_vip_level：", user_vip_level)

            if user_vip_level == None:
                raise Exception("链路不规范")
            else:
                if stop == False:
                    if user_vip_level[0] == 3:
                        stop = True

                    self.self_participation(referee_user[0], activityId, bindStoreId,
                                            statisticsType, referee_user[1], stop)

    # 核算代理任务数
    def accounting_agent_tasks(self, agentId, userId, task, activityId, capping, statisticsType):
        self.retailOrderSharing.session.commit()
        amount = self.retailOrderSharing.session.execute(
            "select amount from sign_up_activity_rank_records where user_id = :userId and marketing_activity_id = :targetId limit 1",
            params={"userId": userId, "marketingActivityId": activityId}).first()

        if task != amount[0]:
            print("{}增加任务数错误，预期{}，实际{}".format(userId, task, amount[0]))

        if statisticsType == 1:
            self.retailOrderSharing.session.commit()
            parent = self.retailOrderSharing.session.execute(
                "select ra1.parent_id, ra2.user_id\
                        from retail_agents ra1\
                        inner join retail_agents ra2 on ra2.id = ra1.parent_id\
                        where ra1.id = :agentId limit 1",
                params={"agentId": agentId}).first()
            print("parent：", parent)
            print("capping：", capping)

            if parent != None:
                if parent[0] > 0:
                    if capping == False:
                        if parent[0] == 1:
                            capping = True

                        self.accounting_agent_tasks(parent[0], parent[1], Decimal(str(task / 2)[0:len(str(task / 2).split(".")[0]) + 3]), activityId, capping, statisticsType)

    # 核算上级用户任务数
    def accounting_tasks(self, userId, task, activityId, union, partner, bindStoreId, statisticsType, categoryId):

        self.retailOrderSharing.session.commit()
        referee_user = self.retailOrderSharing.session.execute(
            "select ru.referee_user_id, rv.vip_level\
                    from retail_users ru\
                    inner join retail_vips rv on rv.user_id = ru.referee_user_id\
                    where ru.user_id = :userId",
                    params={"userId": userId}).first()

        self.retailOrderSharing.session.commit()
        amount = self.retailOrderSharing.session.execute(
            "select amount from sign_up_activity_rank_records where user_id = :userId and marketing_activity_id = :targetId limit 1",
            params={"userId": referee_user[0], "marketingActivityId": activityId}).first()

        if task != amount[0]:
            print("{}增加任务数错误，预期{}，实际{}".format(referee_user[0], task, amount[0]))

        if statisticsType == 1:
            if referee_user[1] == 3:
                if categoryId == 20 or categoryId == 21:
                    self.retailOrderSharing.session.commit()
                    retail_agent = self.retailOrderSharing.session.execute(
                        "select rs.retail_agent_id, ra.user_id\
                                from retail_stores rs\
                                inner join retail_agents ra on ra.id = rs.retail_agent_id\
                                where rs.id = :storeId limit 1",
                        params={"storeId": bindStoreId}).first()

                    self.accounting_agent_tasks(retail_agent[0], retail_agent[1], Decimal(str(task / 2)[0:len(str(task / 2).split(".")[0]) + 3]), activityId, False, statisticsType)

            else:
                self.accounting_tasks(referee_user[0], Decimal(str(task / 2)[0:len(str(task / 2).split(".")[0]) + 3]), activityId, union, partner, bindStoreId, statisticsType, categoryId)

            # if referee_user[0] == 1:
            #     if union == 1:
            #         self.retailOrderSharing.session.commit()
            #         amount = self.retailOrderSharing.session.execute(
            #             "select amount from sign_up_activity_rank_records where user_id = :userId and marketing_activity_id = :targetId limit 1",
            #             params={"userId": referee_user[0], "marketingActivityId": activityId}).first()
            #
            #         if task != amount[0]:
            #             print("{}增加任务数错误，预期{}，实际{}".format(referee_user[0], task, amount[0]))
            #
            #     if statisticsType == 1:
            #         self.accounting_tasks(referee_user[0], Decimal(str(task / 2)[0:len(str(task / 2).split(".")[0]) + 3]), activityId, union + 1, partner, bindStoreId, statisticsType, categoryId)
            #
            # elif referee_user[0] == 2:
            #     if partner == 1:
            #         self.retailOrderSharing.session.commit()
            #         amount = self.retailOrderSharing.session.execute(
            #             "select amount from sign_up_activity_rank_records where user_id = :userId and marketing_activity_id = :targetId limit 1",
            #             params={"userId": referee_user[0], "marketingActivityId": activityId}).first()
            #
            #         if task != amount[0]:
            #             print("{}增加任务数错误，预期{}，实际{}".format(referee_user[0], task, amount[0]))
            #
            #     if statisticsType == 1:
            #         self.accounting_tasks(referee_user[0], Decimal(str(task / 2)[0:len(str(task / 2).split(".")[0]) + 3]), activityId, union, partner + 1, bindStoreId, statisticsType, categoryId)
            #
            # elif referee_user[0] == 3:
            #     self.retailOrderSharing.session.commit()
            #     amount = self.retailOrderSharing.session.execute(
            #         "select amount from sign_up_activity_rank_records where user_id = :userId and marketing_activity_id = :targetId limit 1",
            #         params={"userId": referee_user[0], "marketingActivityId": activityId}).first()
            #
            #     if task != amount[0]:
            #         print("{}增加任务数错误，预期{}，实际{}".format(referee_user[0], task, amount[0]))
            #
            #     if statisticsType == 1:
            #         if categoryId == 20 or categoryId == 21:
            #             self.retailOrderSharing.session.commit()
            #             retail_agent = self.retailOrderSharing.session.execute(
            #                 "select rs.retail_agent_id, ra.user_id\
            #                         from retail_stores rs\
            #                         inner join retail_agents ra on ra.id = rs.retail_agent_id\
            #                         where rs.id = :storeId limit 1",
            #                 params={"storeId": bindStoreId}).first()
            #
            #             self.accounting_agent_tasks(retail_agent[0], retail_agent[1], Decimal(str(task / 2)[0:len(str(task / 2).split(".")[0]) + 3]), activityId, False, statisticsType)

    # 核算自身任务数
    def accounting_self_tasks(self, userId, task, activityId, union, partner, bindStoreId, statisticsType, stop):

        self.retailOrderSharing.session.commit()
        amount = self.retailOrderSharing.session.execute(
            "select amount from sign_up_activity_rank_records where user_id = :userId and marketing_activity_id = :targetId limit 1",
            params={"userId": userId, "marketingActivityId": activityId}).first()

        if task != amount[0]:
            print("{}增加任务数错误，预期{}，实际{}".format(userId, task, amount[0]))

        if stop == True:
            return

        if statisticsType == 1:
            self.retailOrderSharing.session.commit()
            referee_user = self.retailOrderSharing.session.execute(
                "select ru.referee_user_id, rv.vip_level\
                        from retail_users ru\
                        inner join retail_vips rv on rv.user_id = ru.referee_user_id\
                        where ru.user_id = :userId",
                params={"userId": userId}).first()

            if stop == False:
                if referee_user[1] == 3:
                    stop = True

                self.accounting_self_tasks(referee_user[0],
                                           Decimal(str(task / 2)[0:len(str(task / 2).split(".")[0]) + 3]), activityId,
                                           union, partner, bindStoreId, statisticsType, stop)

    # 核对报名活动统计
    def check_registration_statistics(self):
        self.retailOrderSharing.session.commit()
        marketing_activity_list = self.retailOrderSharing.session.execute(
            "select id, category_id, statistics_type, is_toll, toll_amount from marketing_activity where status = 1 and release_type = 3 and is_enable = 1 and is_toll = 0").fetchall()

        # marketingActivity = marketing_activity_list[random.randint(0, len(marketing_activity_list) - 1)]

        for marketingActivity in marketing_activity_list:
            # 金额
            if marketingActivity[1] == 17:
                self.retailOrderSharing.session.commit()
                ordinary_retail_user_list = self.retailOrderSharing.session.execute(
                    "select ru.user_id, u.mobile, ua.id, ru.bind_retail_store_id\
                            from retail_users ru\
                            inner join user_addresses ua on ru.user_id = ua.user_id\
                            inner join users u on u.id = ru.user_id\
                            where ru.is_real_name = 1 and ua.is_default = 1\
                            and ru.user_id not in (select rv.user_id from retail_vips rv where rv.vip_level > 2)\
                            and ru.referee_user_id in (select rv1.user_id from retail_vips rv1)\
                            and ru.user_id not in (select mau.user_id from marketing_activity_user mau where mau.id = :activityId)",
                params={"activityId": marketingActivity[0]}).fetchall()
                ordinaryRetailUser = ordinary_retail_user_list[random.randint(0, len(ordinary_retail_user_list) - 1)]

                self.superiors_participate_in_activities(ordinaryRetailUser[0], marketingActivity[0],
                                                         ordinaryRetailUser[3], marketingActivity[2], marketingActivity[1])
                time.sleep(3)

                self.retailOrderSharing.session.commit()
                self.retailOrderSharing.session.execute(
                    "update marketing_activity set activity_start_at = :activityStartAt, sign_end_at = :signEndAt where id = :activityId",
                    params={"activityStartAt": (datetime.datetime.now() + datetime.timedelta(seconds=30)).strftime(
                        "%Y-%m-%d %H:%M:%S"), "signEndAt": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
                        "activityId": marketingActivity[0]})
                self.retailOrderSharing.session.commit()
                time.sleep(240)

                requests.request("POST", url="https://test.api.vodeshop.com/api/sms/user-login",
                                 json={"mobile": ordinaryRetailUser[1]})
                time.sleep(5)

                print("ordinaryRetailUser：", ordinaryRetailUser)
                userToken = requests.request("POST", url="https://test.api.vodeshop.com/api/auth/login/mobile",
                                             json={"mobile": ordinaryRetailUser[1], "password": "", "code": "111111"}).json()
                print("userToken：", userToken)
                token = userToken["data"]["token_type"] + " " + userToken["data"]["access_token"]

                goodList = requests.request("GET",
                                            url="https://test.api.vodeshop.com/api/retail/mall/index-goods?page=" + str(
                                                random.randint(1, 4)),
                                            headers={"x-request-from": "web", "x-requested-with": "XMLHttpRequest",
                                                     "authorization": token}).json()["data"]["data"]
                good = goodList[random.randint(0, 14)]
                print("good：", good)

                goodSkuList = requests.request("GET",
                                               url="https://test.api.vodeshop.com/api/retail/goods/show?retail_goods_id=" + str(
                                                   good["id"]),
                                               headers={"x-request-from": "web", "x-requested-with": "XMLHttpRequest",
                                                        "authorization": token}).json()["data"]["goods_skus"]
                goodSku = None
                if len(goodSkuList) == 1:
                    goodSku = goodSkuList[0]
                elif len(goodSkuList) > 1:
                    goodSku = goodList[random.randint(0, random.randint(0, len(goodSkuList) - 1))]
                print("goodSku：", goodSku)

                goodTotal = random.randint(2, 3)

                orderCheck = requests.request("POST", url="https://test.api.vodeshop.com/api/retail/check-order",
                                              headers={"x-request-from": "web", "x-requested-with": "XMLHttpRequest",
                                                       "authorization": token},
                                              json={"retail_goods_id": [good["id"]], "address_id": ordinaryRetailUser[2]}).json()
                confirm = requests.request("POST", url="https://test.api.vodeshop.com/api/retail/order/confirm",
                                           headers={"x-request-from": "web", "x-requested-with": "XMLHttpRequest",
                                                    "authorization": token}, json={
                        "goods": [{"goods_sku_id": goodSku["id"], "goods_total": goodTotal}], "cart_id": [],
                        "address_id": ordinaryRetailUser[2]}).json()
                print("confirm：", confirm)
                order = requests.request("POST", url="https://test.api.vodeshop.com/api/retail/order/order",
                                         headers={"x-request-from": "web", "x-requested-with": "XMLHttpRequest",
                                                  "authorization": token}, json={
                        "goods": [{"goods_sku_id": goodSku["id"], "goods_total": goodTotal}], "cart_id": [],
                        "address_id": ordinaryRetailUser[2], "pay_type": 1}).json()
                print("order：", order)

                goods_sku = confirm["data"]["goods"][0]["items"][0]["goods_sku"]
                amount = (decimal.Decimal(goods_sku["price"]) + decimal.Decimal(
                    orderCheck["data"][0]["addr_carriage"]) - decimal.Decimal(goods_sku["sub_price"])) * goodTotal
                print("amount：", amount)
                self.retailOrderSharing.session.commit()
                order_sn = self.retailOrderSharing.session.execute(
                    "select order_sn from payments where user_id = :userId and targetable_id =:targetableId order by created_at desc limit 1",
                    params={"userId": ordinaryRetailUser[0], "targetableId": order["data"]["order_merge_id"]}).first()
                print("order_sn：", order_sn)

                res = requests.request("POST", url="https://test.api.vodeshop.com/api/v2/test/notifyyyy",
                                       data={"out_trade_no": order_sn[0], "trade_no": order_sn[0],
                                             "total_amount": "1"}).json()
                print("res：", res)
                time.sleep(5)

                self.accounting_tasks(ordinaryRetailUser[0], amount, marketingActivity[0], 1, 1,
                                      ordinaryRetailUser[3], marketingActivity[2], marketingActivity[1])

            # 拉新
            elif marketingActivity[1] == 18:
                self.retailOrderSharing.session.commit()
                invitation_retail_user_list = self.retailOrderSharing.session.execute(
                    "select ru.user_id, u.mobile, ua.id, ru.bind_retail_store_id, rv.vip_level\
                            from retail_users ru\
                            inner join user_addresses ua on ru.user_id = ua.user_id\
                            inner join users u on u.id = ru.user_id\
                            inner join retail_vips rv on rv.user_id = ru.user_id\
                            where ru.is_real_name = 1 and ua.is_default = 1\
                            and ru.user_id not in (select mau.user_id from marketing_activity_user mau where mau.id = :activityId)",
                params={"activityId": marketingActivity[0]}).fetchall()
                invitationRetailUser = invitation_retail_user_list[
                    random.randint(0, len(invitation_retail_user_list) - 1)]

                stop = False
                if invitationRetailUser[4] == 3:
                    stop = True

                self.self_participation(invitationRetailUser[0], marketingActivity[0],
                                                         invitationRetailUser[3], marketingActivity[2], invitationRetailUser[1], stop)
                time.sleep(3)

                self.retailOrderSharing.session.commit()
                self.retailOrderSharing.session.execute(
                    "update marketing_activity set activity_start_at = :activityStartAt, sign_end_at = :signEndAt where id = :activityId",
                    params={"activityStartAt": (datetime.datetime.now() + datetime.timedelta(seconds=30)).strftime(
                        "%Y-%m-%d %H:%M:%S"), "signEndAt": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
                        "activityId": marketingActivity[0]})
                self.retailOrderSharing.session.commit()
                time.sleep(240)

                # 邀请好友逻辑
                time.sleep(3)

                self.accounting_self_tasks(invitationRetailUser[0], Decimal("1.00"), marketingActivity[0], 1, 1,
                                      invitationRetailUser[3], marketingActivity[2], stop)

            # 拉新并下单
            elif marketingActivity[1] == 19:
                self.retailOrderSharing.session.commit()
                invitation_retail_user_list = self.retailOrderSharing.session.execute(
                    "select ru.user_id, u.mobile, ua.id, ru.bind_retail_store_id, rv.vip_level\
                            from retail_users ru\
                            inner join user_addresses ua on ru.user_id = ua.user_id\
                            inner join users u on u.id = ru.user_id\
                            inner join retail_vips rv on rv.user_id = ru.user_id\
                            where ru.is_real_name = 1 and ua.is_default = 1\
                            and ru.user_id not in (select mau.user_id from marketing_activity_user mau where mau.id = :activityId)",
                    params={"activityId": marketingActivity[0]}).fetchall()
                invitationRetailUser = invitation_retail_user_list[
                    random.randint(0, len(invitation_retail_user_list) - 1)]

                stop = False
                if invitationRetailUser[4] == 3:
                    stop = True

                self.self_participation(invitationRetailUser[0], marketingActivity[0],
                                        invitationRetailUser[3], marketingActivity[2], invitationRetailUser[1], stop)
                time.sleep(3)

                self.retailOrderSharing.session.commit()
                self.retailOrderSharing.session.execute(
                    "update marketing_activity set activity_start_at = :activityStartAt, sign_end_at = :signEndAt where id = :activityId",
                    params={"activityStartAt": (datetime.datetime.now() + datetime.timedelta(seconds=30)).strftime(
                        "%Y-%m-%d %H:%M:%S"), "signEndAt": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
                        "activityId": marketingActivity[0]})
                self.retailOrderSharing.session.commit()
                time.sleep(240)

                # 邀请好友，并且被邀请的好友下单......

                self.accounting_self_tasks(invitationRetailUser[0], Decimal("1.00"), marketingActivity[0], 1, 1,
                                           invitationRetailUser[3], marketingActivity[2], stop)

            # 联合店长
            elif marketingActivity[1] == 20:
                self.retailOrderSharing.session.commit()
                ordinary_retail_user_list = self.retailOrderSharing.session.execute(
                    "select ru.user_id, u.mobile, ua.id, ru.bind_retail_store_id\
                            from retail_users ru\
                            inner join user_addresses ua on ru.user_id = ua.user_id\
                            inner join users u on u.id = ru.user_id\
                            where ru.is_real_name = 1 and ua.is_default = 1\
                            and ru.user_id not in (select rv.user_id from retail_vips rv)\
                            and ru.referee_user_id in (select rv1.user_id from retail_vips rv1)\
                            and ru.user_id not in (select mau.user_id from marketing_activity_user mau where mau.id = :activityId)",
                params={"activityId": marketingActivity[0]}).fetchall()
                ordinaryRetailUser = ordinary_retail_user_list[random.randint(0, len(ordinary_retail_user_list) - 1)]

                self.superiors_participate_in_activities(ordinaryRetailUser[0], marketingActivity[0], ordinaryRetailUser[3], marketingActivity[2], marketingActivity[1])
                time.sleep(3)

                self.retailOrderSharing.session.commit()
                self.retailOrderSharing.session.execute(
                    "update marketing_activity set activity_start_at = :activityStartAt, sign_end_at = :signEndAt where id = :activityId",
                    params={"activityStartAt": (datetime.datetime.now() + datetime.timedelta(seconds=30)).strftime(
                        "%Y-%m-%d %H:%M:%S"), "signEndAt": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
                        "activityId": marketingActivity[0]})
                self.retailOrderSharing.session.commit()
                time.sleep(240)

                requests.request("POST", url="https://test.api.vodeshop.com/api/sms/user-login",
                                 json={"mobile": ordinaryRetailUser[1]})
                time.sleep(5)

                print("ordinaryRetailUser：", ordinaryRetailUser)
                userToken = requests.request("POST", url="https://test.api.vodeshop.com/api/auth/login/mobile",
                                             json={"mobile": ordinaryRetailUser[1], "password": "", "code": "111111"}).json()
                print("userToken：", userToken)
                token = userToken["data"]["token_type"] + " " + userToken["data"]["access_token"]

                order = requests.request("post",
                                                "https://test.api.vodeshop.com/api/retail/vip/order",
                                                headers={"x-request-from":"web","x-requested-with":"XMLHttpRequest","authorization":token},
                                                json={"id": 1, "gift_id": "1",
                                                      "address_id": ordinaryRetailUser[2],
                                                      "pay_type": 1}).json()
                print(order)
                print(order["data"]["order_id"])
                time.sleep(5)

                self.retailOrderSharing.session.commit()
                order_sn = self.retailOrderSharing.session.execute(
                    "select order_sn from payments where user_id = :userId and targetable_id =:targetableId order by created_at desc limit 1",
                    params={"userId": ordinaryRetailUser[0], "targetableId": order["data"]["order_merge_id"]}).first()
                print("order_sn：", order_sn)

                res = requests.request("POST", url="https://test.api.vodeshop.com/api/v2/test/notifyyyy",
                                       data={"out_trade_no": order_sn[0], "trade_no": order_sn[0],
                                             "total_amount": "1"}).json()
                print("res：", res)
                time.sleep(3)

                self.accounting_tasks(ordinaryRetailUser[0], Decimal("1.00"), marketingActivity[0], 1, 1, ordinaryRetailUser[3], marketingActivity[2], marketingActivity[1])

            # 店铺合伙人
            elif marketingActivity[1] == 21:
                self.retailOrderSharing.session.commit()
                ordinary_retail_user_list = self.retailOrderSharing.session.execute(
                    "select ru.user_id, u.mobile, ua.id, ru.bind_retail_store_id\
                            from retail_users ru\
                            inner join user_addresses ua on ru.user_id = ua.user_id\
                            inner join users u on u.id = ru.user_id\
                            where ru.is_real_name = 1 and ua.is_default = 1\
                            and ru.user_id not in (select rv.user_id from retail_vips rv where rv.vip_level in (2, 3))\
                            and ru.referee_user_id in (select rv1.user_id from retail_vips rv1 where rv1.vip_level > 1)\
                            and ru.user_id not in (select mau.user_id from marketing_activity_user mau where mau.id = :activityId)",
                    params={"activityId": marketingActivity[0]}).fetchall()
                ordinaryRetailUser = ordinary_retail_user_list[random.randint(0, len(ordinary_retail_user_list) - 1)]

                self.superiors_participate_in_activities(ordinaryRetailUser[0], marketingActivity[0],
                                                         ordinaryRetailUser[3], marketingActivity[2],
                                                         marketingActivity[1])
                time.sleep(3)

                self.retailOrderSharing.session.commit()
                self.retailOrderSharing.session.execute(
                    "update marketing_activity set activity_start_at = :activityStartAt, sign_end_at = :signEndAt where id = :activityId",
                    params={"activityStartAt": (datetime.datetime.now() + datetime.timedelta(seconds=30)).strftime(
                        "%Y-%m-%d %H:%M:%S"), "signEndAt": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
                        "activityId": marketingActivity[0]})
                self.retailOrderSharing.session.commit()
                time.sleep(240)

                # 购买店铺合伙人礼包逻辑......

                self.accounting_tasks(ordinaryRetailUser[0], Decimal("1.00"), marketingActivity[0], 1, 1,
                                      ordinaryRetailUser[3], marketingActivity[2], marketingActivity[1])

            # 标准店主
            elif marketingActivity[1] == 22:
                self.retailOrderSharing.session.commit()
                ordinary_retail_user_list = self.retailOrderSharing.session.execute(
                    "select ru.user_id, u.mobile, ua.id, ru.bind_retail_store_id\
                            from retail_users ru\
                            inner join user_addresses ua on ru.user_id = ua.user_id\
                            inner join users u on u.id = ru.user_id\
                            where ru.is_real_name = 1 and ua.is_default = 1\
                            and ru.user_id not in (select rv.user_id from retail_vips rv where rv.vip_level > 2)\
                            and ru.user_id not in (select mau.user_id from marketing_activity_user mau where mau.id = :activityId)\
                            and ru.user_id not in (select ra.user_id from retail_agents ra)",
                    params={"activityId": marketingActivity[0]}).fetchall()
                ordinaryRetailUser = ordinary_retail_user_list[random.randint(0, len(ordinary_retail_user_list) - 1)]

                self.retailOrderSharing.session.commit()
                retail_agent_list = self.retailOrderSharing.session.execute(
                    "select ra.id, ra.user_id, u.mobile\
                    from retail_agents ra\
                    inner join users u on u.id = ra.user_id").fetchall()
                retailAgent = retail_agent_list[random.randint(0, len(retail_agent_list) - 1)]

                self.participate_in_the_event_as_an_agent(retailAgent[0], retailAgent[1], marketingActivity[0], False,
                                                          retailAgent[2], marketingActivity[2])
                time.sleep(3)

                self.retailOrderSharing.session.commit()
                self.retailOrderSharing.session.execute(
                    "update marketing_activity set activity_start_at = :activityStartAt, sign_end_at = :signEndAt where id = :activityId",
                    params={"activityStartAt": (datetime.datetime.now() + datetime.timedelta(seconds=30)).strftime(
                        "%Y-%m-%d %H:%M:%S"), "signEndAt": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
                        "activityId": marketingActivity[0]})
                self.retailOrderSharing.session.commit()
                time.sleep(240)

                # 升级店主逻辑......

                self.accounting_agent_tasks(retailAgent[0], retailAgent[1], Decimal("1.00"), marketingActivity[0],
                                            False, marketingActivity[2])

            # 区代
            elif marketingActivity[1] == 23:
                self.retailOrderSharing.session.commit()
                ordinary_retail_user_list = self.retailOrderSharing.session.execute(
                    "select ru.user_id, u.mobile, ua.id, ru.bind_retail_store_id\
                            from retail_users ru\
                            inner join user_addresses ua on ru.user_id = ua.user_id\
                            inner join users u on u.id = ru.user_id\
                            where ru.is_real_name = 1 and ua.is_default = 1\
                            and ru.user_id not in (select mau.user_id from marketing_activity_user mau where mau.id = :activityId)\
                            and ru.user_id not in (select ra.user_id from retail_agents ra)",
                params={"activityId": marketingActivity[0]}).fetchall()
                ordinaryRetailUser = ordinary_retail_user_list[random.randint(0, len(ordinary_retail_user_list) - 1)]

                self.retailOrderSharing.session.commit()
                retail_agent_list = self.retailOrderSharing.session.execute(
                    "select ra.id, ra.user_id, u.mobile\
                    from retail_agents ra\
                    inner join users u on u.id = ra.user_id").fetchall()
                retailAgent = retail_agent_list[random.randint(0, len(retail_agent_list) - 1)]

                self.participate_in_the_event_as_an_agent(retailAgent[0], retailAgent[1], marketingActivity[0], False, retailAgent[2], marketingActivity[2])
                time.sleep(3)

                self.retailOrderSharing.session.commit()
                self.retailOrderSharing.session.execute(
                    "update marketing_activity set activity_start_at = :activityStartAt, sign_end_at = :signEndAt where id = :activityId",
                    params={"activityStartAt": (datetime.datetime.now() + datetime.timedelta(seconds=30)).strftime(
                        "%Y-%m-%d %H:%M:%S"), "signEndAt": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
                        "activityId": marketingActivity[0]})
                self.retailOrderSharing.session.commit()
                time.sleep(240)

                requests.request("POST", url="https://test.api.vodeshop.com/api/sms/user-login",
                                 json={"mobile": ordinaryRetailUser[1]})
                time.sleep(5)

                print("ordinaryRetailUser：", ordinaryRetailUser)
                userToken = requests.request("POST", url="https://test.api.vodeshop.com/api/auth/login/mobile",
                                             json={"mobile": ordinaryRetailUser[1], "password": "",
                                                   "code": "111111"}).json()
                print("userToken：", userToken)
                token = userToken["data"]["token_type"] + " " + userToken["data"]["access_token"]

                requests.request("POST", url="https://test.api.vodeshop.com/api/retail/agent/apply",
                                 headers={"x-request-from": "web", "x-requested-with": "XMLHttpRequest",
                                          "authorization": token},
                                   json={"agent_level":1,"agent_name":"小区代","agent_mobile":ordinaryRetailUser[1],"province":"广东","province_id":"19",
                                         "city":"广州市","city_id":"1601","area":"番禺区","area_id":"36953","address":"节能科技园10号楼"})

                self.retailOrderSharing.session.commit()
                self.retailOrderSharing.session.execute(
                    "update retail_agent_apply_records set audit_status = 1 where user_id =:userId and agent_level = :agentLevel",
                    params={"userId": ordinaryRetailUser[0], "agentLevel": 1})
                self.retailOrderSharing.session.commit()

                self.retailOrderSharing.session.commit()
                self.retailOrderSharing.session.execute(
                    "insert into retail_agents(user_id, parent_id, agent_level, status, store_num, use_store_num, province_id, province, city_id, city, area_id, area,  address, agent_name, agent_mobile)\
                        values(:userId, :parenId, :agentLevel, :status, :storeNum, :useStoreNum, :provinceId, :province, :cityId, :city, :areaId, :area,  :address, :agentName, :agentMobile)",
                    params={"userId": ordinaryRetailUser[0], "parenId": retailAgent[0], "agentLevel": 1, "status": 1,
                            "storeNum": 10, "useStoreNum": 0, "provinceId": 19, "province": "广东省", "cityId": "广州市", 1601: "广州市", "areaId": 36953, "area": "番禺区",
                            "address": "节能科技园10号楼", "agentName": "小区代", "agentMobile": ordinaryRetailUser[1]})
                self.retailOrderSharing.session.commit()
                time.sleep(3)

                self.accounting_agent_tasks(retailAgent[0], retailAgent[1], Decimal("1.00"), marketingActivity[0], False, marketingActivity[2])

            # 市代
            elif marketingActivity[1] == 24:
                self.retailOrderSharing.session.commit()
                ordinary_retail_user_list = self.retailOrderSharing.session.execute(
                    "select ru.user_id, u.mobile, ua.id, ru.bind_retail_store_id\
                            from retail_users ru\
                            inner join user_addresses ua on ru.user_id = ua.user_id\
                            inner join users u on u.id = ru.user_id\
                            where ru.is_real_name = 1 and ua.is_default = 1\
                            and ru.user_id not in (select mau.user_id from marketing_activity_user mau where mau.id = :activityId)\
                            and ru.user_id not in (select ra.user_id from retail_agents ra where ra.agent_level > 1)",
                    params={"activityId": marketingActivity[0]}).fetchall()
                ordinaryRetailUser = ordinary_retail_user_list[random.randint(0, len(ordinary_retail_user_list) - 1)]

                self.retailOrderSharing.session.commit()
                market_agent_list = self.retailOrderSharing.session.execute(
                    "select ra.id, ra.user_id, u.mobile\
                    from retail_agents ra\
                    inner join users u on u.id = ra.user_id\
                    where ra.agent_level = 2").fetchall()
                marketAgent = market_agent_list[random.randint(0, len(market_agent_list) - 1)]

                self.participate_in_the_event_as_an_agent(marketAgent[0], marketAgent[1], marketingActivity[0], False,
                                                          marketAgent[2], marketingActivity[2])
                time.sleep(3)

                self.retailOrderSharing.session.commit()
                self.retailOrderSharing.session.execute(
                    "update marketing_activity set activity_start_at = :activityStartAt, sign_end_at = :signEndAt where id = :activityId",
                    params={"activityStartAt": (datetime.datetime.now() + datetime.timedelta(seconds=30)).strftime(
                        "%Y-%m-%d %H:%M:%S"), "signEndAt": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
                        "activityId": marketingActivity[0]})
                self.retailOrderSharing.session.commit()
                time.sleep(240)

                # 升级市代逻辑......

                self.accounting_agent_tasks(marketAgent[0], marketAgent[1], Decimal("1.00"), marketingActivity[0],
                                            False, marketingActivity[2])
